<?php
/**
 * @Author: dxf
 * @Date: 2020-03-16
 * @Time: 17:21
 */

/**
 * 任务
 */
class Job{


    /**
     * worker进程数量
     * @var int
     */
    protected $worker_num = 5;

    /**
     * manager进程数量
     * @var int
     */
    protected $manager_num = 2;


    public function __construct()
    {
        $this->createManger();
        $this->createWorker();
        $this->monitor();
    }


    /**
     * 创建worker
     */
    public function createWorker(){
        for($i=0;$i<$this->worker_num;$i++){
            $process = new \Swoole\Process(function(){
                //子进程空间执行业务逻辑
                sleep(20);
                echo getmypid()."正在执行业务".PHP_EOL;
            });
            $process->start();
        }
    }


    /**
     * 创建manger
     */
    public function createManger(){
        for($i=0;$i<$this->manager_num;$i++){
            $process = new \Swoole\Process(function(){
                //子进程空间执行业务逻辑
                sleep(20);
                echo getmypid()."正在执行业务".PHP_EOL;
            });
            $process->start();
        }
    }


    /**
     * 监听结果
     */
    public function monitor(){
        //正常回收结束运行的子进程。  还有异常的没有写进来
        while($res = \Swoole\Process::wait(true)){
            echo "PID={$res['pid']}".PHP_EOL;
        }
    }

}


//应该在外面传入一个function，然后执行业务
//$job = new Job();
//$job->on('manager',function(){
//
//});

$job = new Job();
